<template>
  <div class="goods-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索商品名称/编号/分类"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增商品
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredGoods" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="goodsId" label="商品编号" width="192" sortable align="center" />
      <el-table-column prop="name" label="商品名称" width="150" align="center"/>
      <el-table-column prop="category" label="分类" width="120" align="center">
        <template #default="{ row }">
          <el-tag effect="plain" :type="categoryTagType[row.category]">
            {{ row.category }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格(元)" width="120" sortable align="center" />
      <el-table-column prop="stock" label="库存状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="stockTagType[row.stock]" effect="light">
            {{ stockStatusMap[row.stock] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="origin" label="产地" width="150" />
      <el-table-column prop="status" label="商品状态" width="120" align="center">
        <template #default="{ row }">
          <span :style="{ color: statusColorMap[row.status] }">{{ row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="shelfDate" label="上架日期" width="200" sortable  align="center"/>
      <el-table-column prop="description" label="商品描述" width="260" align="center"/>
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.goodsId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑商品信息' : '新增商品信息'"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="商品编号" prop="goodsId">
          <el-input 
            v-model="formData.goodsId" 
            :disabled="isEditMode"
            placeholder="请输入商品编号（如：FD2024001）"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input 
            v-model="formData.name"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select 
            v-model="formData.category"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :max="9999"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存状态" prop="stock">
          <el-select 
            v-model="formData.stock"
            placeholder="请选择库存状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in stockOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-select 
            v-model="formData.origin"
            placeholder="请选择产地"
            style="width: 100%"
          >
            <el-option
              v-for="item in origins"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select 
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上架日期" prop="shelfDate">
          <el-date-picker
            v-model="formData.shelfDate"
            type="date"
            placeholder="选择上架日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            type="textarea"
            v-model="formData.description" 
            rows="2"
            placeholder="请输入商品描述"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// SessionStorage 操作工具
const STORAGE_KEY = 'goods_management_state'
const saveToStorage = (state) => {
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state))
}
const loadFromStorage = () => {
  const data = sessionStorage.getItem(STORAGE_KEY)
  return data ? JSON.parse(data) : {}
}

// 分类配置
const categories = [
  '饮品',
  '主食',
  '甜点',
  '快餐',
  '海鲜',
  '水果'
]

// 产地配置
const origins = [
  '本地采购',
  '山东产地',
  '广东产地',
  '进口商品',
  '云南产地',
  '新疆产地'
]

// 状态配置
const statusList = [
  '热销中',
  '常规供应',
  '即将下架'
]

// 库存选项
const stockOptions = [
  { value: 0, label: '库存充足' },
  { value: 1, label: '库存紧张' },
  { value: 2, label: '暂时缺货' }
]

// 标签样式映射
const categoryTagType = {
  '饮品': 'info',
  '主食': 'warning',
  '甜点': 'danger',
  '快餐': '',
  '海鲜': 'success',
  '水果': 'primary'
}

const stockTagType = {
  0: 'success',
  1: 'warning',
  2: 'danger'
}

const stockStatusMap = {
  0: '充足',
  1: '紧张',
  2: '缺货'
}

const statusColorMap = {
  '热销中': '#e74c3c',
  '常规供应': '#2ecc71',
  '即将下架': '#95a5a6'
}

// 初始化状态（优先从 SessionStorage 加载）
const storedState = loadFromStorage()

// 商品数据（带存储恢复）
const goodsList = ref(storedState.goodsList || [
  {
    goodsId: 'FD2024001',
    name: '金汤肥牛面',
    category: '主食',
    price: 38.9,
    stock: 0,
    origin: '本地采购',
    status: '热销中',
    shelfDate: '2024-03-15',
    description: '精选肥牛配特制金汤，微辣口感'
  },
  {
    goodsId: 'FD2024002',
    name: '杨枝甘露',
    category: '饮品',
    price: 22.5,
    stock: 1,
    origin: '广东产地',
    status: '常规供应',
    shelfDate: '2024-02-20',
    description: '新鲜芒果搭配西柚粒，经典港式甜品'
  },
  {
    goodsId: 'FD2024003',
    name: '黑椒牛排',
    category: '快餐',
    price: 68.0,
    stock: 0,
    origin: '进口商品',
    status: '热销中',
    shelfDate: '2024-01-10',
    description: '澳洲谷饲牛排配秘制黑椒汁'
  },
  {
    goodsId: 'FD2024004',
    name: '榴莲千层',
    category: '甜点',
    price: 39.9,
    stock: 2,
    origin: '云南产地',
    status: '即将下架',
    shelfDate: '2023-12-01',
    description: '泰国金枕榴莲，手工千层制作'
  },
  {
    goodsId: 'FD2024005',
    name: '麻辣小龙虾',
    category: '海鲜',
    price: 128.0,
    stock: 0,
    origin: '湖北产地',
    status: '常规供应',
    shelfDate: '2024-04-12',
    description: '鲜活小龙虾，地道麻辣口味'
  },
  {
    goodsId: 'FD2024006',
    name: '新疆哈密瓜',
    category: '水果',
    price: 25.8,
    stock: 0,
    origin: '新疆产地',
    status: '常规供应',
    shelfDate: '2024-05-05',
    description: '当季新鲜哈密瓜，甜度达15°'
  },
  {
    goodsId: 'FD2024007',
    name: '珍珠奶茶',
    category: '饮品',
    price: 18.0,
    stock: 1,
    origin: '本地采购',
    status: '热销中',
    shelfDate: '2024-03-28',
    description: '经典台奶配方，Q弹黑糖珍珠'
  },
  {
    goodsId: 'FD2024008',
    name: '和牛汉堡',
    category: '快餐',
    price: 58.0,
    stock: 0,
    origin: '进口商品',
    status: '常规供应',
    shelfDate: '2024-04-19',
    description: '澳洲和牛制作，双层芝士配置'
  },
  {
    goodsId: 'FD2024009',
    name: '抹茶慕斯',
    category: '甜点',
    price: 32.9,
    stock: 0,
    origin: '本地采购',
    status: '常规供应',
    shelfDate: '2024-05-10',
    description: '宇治抹茶制作，入口即化'
  },
  {
    goodsId: 'FD2024010',
    name: '三文鱼刺身',
    category: '海鲜',
    price: 88.0,
    stock: 2,
    origin: '挪威进口',
    status: '即将下架',
    shelfDate: '2024-04-22',
    description: '挪威深海三文鱼，厚切刺身'
  }
])

// 搜索功能
const searchText = ref(storedState.searchText || '')
const filteredGoods = computed(() => {
  const search = searchText.value.toLowerCase()
  return goodsList.value.filter(goods => 
    goods.goodsId.toLowerCase().includes(search) ||
    goods.name.toLowerCase().includes(search) ||
    goods.category.toLowerCase().includes(search) ||
    goods.origin.toLowerCase().includes(search)
  )
})

// 对话框相关状态（带存储恢复）
const dialogVisible = ref(storedState.dialogVisible || false)
const isEditMode = ref(storedState.isEditMode || false)
const formRef = ref(null)
const formData = reactive(storedState.formData || {
  goodsId: '',
  name: '',
  category: '主食',
  price: 20.0,
  stock: 0,
  origin: '本地采购',
  status: '常规供应',
  shelfDate: new Date().toISOString().split('T')[0],
  description: ''
})

// 表单验证规则
const formRules = {
  goodsId: [
    { required: true, message: '商品编号不能为空', trigger: 'blur' },
    { pattern: /^FD\d{7}$/, message: '编号格式：FD+7位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  category: { required: true, message: '请选择分类', trigger: 'change' },
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '价格范围0-9999元', trigger: 'blur' }
  ],
  origin: { required: true, message: '请选择产地', trigger: 'change' }
}

// 状态变化时自动保存到 SessionStorage
watch([goodsList, searchText, dialogVisible, isEditMode, () => ({ ...formData })], () => {
  saveToStorage({
    goodsList: goodsList.value,
    searchText: searchText.value,
    dialogVisible: dialogVisible.value,
    isEditMode: isEditMode.value,
    formData: { ...formData }
  })
}, { deep: true })

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (goodsId) => {
  ElMessageBox.confirm('此操作将永久删除该商品，是否继续？', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    goodsList.value = goodsList.value.filter(g => g.goodsId !== goodsId)
    ElMessage.success('商品删除成功')
  }).catch(() => {})
}

// 提交表单（补全逻辑）
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = goodsList.value.findIndex(g => g.goodsId === formData.goodsId)
    goodsList.value.splice(index, 1, { ...formData })
  } else {
    // 检查商品编号是否已存在
    if (goodsList.value.some(g => g.goodsId === formData.goodsId)) {
      return ElMessage.warning('商品编号已存在，请修改')
    }
    goodsList.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '商品信息已更新' : '新增商品成功')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    goodsId: '',
    name: '',
    category: '主食',
    price: 20.0,
    stock: 0,
    origin: '本地采购',
    status: '常规供应',
    shelfDate: new Date().toISOString().split('T')[0],
    description: ''
  })
}
</script>

<style scoped lang="scss">
.goods-management {
  padding: 24px;
  background: #fff8f5;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(231,76,60,0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #fff8f5 !important;
    color: #e67e22;
    font-weight: 600;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(231,76,60,0.08);
  }

  .el-tag {
    font-size: 13px;
    padding: 0 8px;
    height: 26px;
    line-height: 24px;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #ffe0b2;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ffe0b2;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>